<template>
  <div class="application-list-container">
    <el-dialog
      width="600px"
      title="应用参数列表"
      :visible.sync="dialogVisible"
    >
      <el-table
        stripe
        :data="showParamiterData"
      >
        <el-table-column
          prop="name"
          label="参数名"
        ></el-table-column>
        <el-table-column
          prop="value"
          label="参数值"
        ></el-table-column>
      </el-table>
      <div class="receive-device-footer">
        <el-pagination
          background="#fff"
          @size-change="pageSizeChangeHandler"
          @current-change="currentPageChangeHandler"
          :current-page.sync="searchFormDialog.currentPage"
          :page-size.sync="searchFormDialog.pageSize"
          :page-sizes="[5, 10, 20, 50, 100]"
          layout="total,sizes, prev, pager, next, jumper"
          :total="searchFormDialog.totalCount"
          align="center"
        ></el-pagination>
      </div>
    </el-dialog>
    <edit
      ref="editComponent"
      @refresh="search"
    ></edit>
    <header-search-form
      :searchFormData="searchForm"
      @search="search"
    />
    <lan-table
      size="small"
      :config="dataTable"
      :tableData="tableData"
      @search="search"
    >
      <template #type="scope">
        <el-input v-model="scope.row.type"></el-input>
      </template>
      <template #organizationList="scope">
        <el-tag
          size="small"
          class="orgnization-tag"
          v-for="value in scope.row.organizationList"
          :key="value.id"
        >{{ value.name }}</el-tag>
      </template>
    </lan-table>
  </div>
</template>

<script>
import lanTable from '../../../components/lanTable';
import HeaderSearchForm from './headerSearchForm.vue';
import moment from 'moment';
import Edit from './edit';
import { MomentFormat, SortType } from '../../../constants/common';
import { Message, MessageBox } from 'element-ui';
import { deleteApplicationApi, getApplicationListApi } from '../../../api/application';
import { parseError } from '../../../utils';
import { getActiveDisplay, getActiveColor } from './service';

export default {
  components: {
    Edit,
    lanTable,
    HeaderSearchForm
  },
  data() {
    return {
      dataTable: {
        pageSize: 10,
        totalCount: 0,
        currentPage: 1,
        pageSizes: [5, 10, 20, 50, 100],
        sort: {
          sortType: SortType.DESC,
          orderBy: 'createAt'
        },
        columnList: [
          {
            name: 'index',
            label: '',
            type: 'index'
          },
          {
            name: 'name',
            label: '名称'
          },
          {
            name: 'organizationList',
            type: 'slot',
            label: '组织'
          },
          {
            name: 'appId',
            label: 'appId'
          },
          {
            label: '是否可用',
            type: 'formatter',
            name: 'active',
            scope: true,
            formatter: getActiveDisplay,
            style: {
              color: getActiveColor
            }
          },
          {
            label: '应用参数',
            type: 'button',
            name: 'settingList',
            scope: true,
            buttons: [{ isShow: true, size: 'small', text: '查看', icon: 'el-icon-tickets', method: row => this.checkSetting(row) }]
          },
          {
            name: 'createdAt',
            label: '创建时间',
            sortable: true
          },
          {
            name: 'updatedAt',
            label: '更新时间'
          },
          {
            type: 'button',
            label: '操作',
            buttons: [
              {
                isShow: () => this.userGuardList.includes(this.guard.DeviceTypeManage),
                type: 'text',
                text: '编辑',
                size: 'small',
                method: row => {
                  this.showEdit(row);
                }
              },
              {
                isShow: () => this.userGuardList.includes(this.guard.DeviceTypeManage),
                type: 'text',
                text: '删除',
                size: 'small',
                method: row => {
                  this.remove(row.uuid, row.name);
                }
              }
            ]
          }
        ]
      },
      searchForm: {
        btnLoading: false,
        name: '',
        active: ''
      },
      tableData: [],
      dialogVisible: false,
      settingList: [],
      searchFormDialog: {
        currentPage: 1,
        pageSize: 10,
        totalCount: 0
      },
      showParamiterData: []
    };
  },
  created() {
    this.search();
  },
  watch: {
    deviceParameterList: {
      handler(val) {
        this.searchFormDialog.totalCount = val.length;
        this.searchDialog();
      }
    }
  },
  methods: {
    getActiveDisplay,
    getActiveColor,
    searchDialog() {
      this.showParamiterData = this.settingList.slice(
        (this.searchFormDialog.currentPage - 1) * this.searchFormDialog.pageSize,
        this.searchFormDialog.currentPage * this.searchFormDialog.pageSize
      );
    },
    pageSizeChangeHandler() {
      this.searchFormDialog.currentPage = 1;
      this.searchDialog();
    },
    currentPageChangeHandler() {
      this.searchDialog();
    },
    search() {
      this.searchForm.btnLoading = true;
      getApplicationListApi(this.dataTable.currentPage - 1, this.dataTable.pageSize, this.dataTable.sort.sortType, this.searchForm.name)
        .then(res => {
          this.dataTable.totalCount = res.total_count;
          this.tableData = res.data.map(item => {
            const settingList = [];
            for (const key in item.setting) {
              settingList.push({
                name: key,
                value: item.setting[key],
                key
              });
            }
            return {
              uuid: item.uuid,
              name: item.name,
              setting: item.setting,
              organizationList: item.organization_list,
              appId: item.app_id,
              createdAt: moment(item.created_at).format(MomentFormat),
              updatedAt: moment(item.updated_at).format(MomentFormat),
              settingList,
              active: item.active
            };
          });
        })
        .catch(error => Message.error(parseError(error)))
        .finally(() => (this.searchForm.btnLoading = false));
    },
    showEdit(row) {
      this.$refs.editComponent.showDialog(row);
    },
    checkSetting(row) {
      this.settingList = row.settingList;
      this.searchDialog();
      this.$nextTick(() => {
        this.searchFormDialog.totalCount = this.settingList.length;
        this.searchDialog();
      });
      this.dialogVisible = true;
    },
    remove(uuid, name) {
      MessageBox.confirm(`确定删除应用${name}吗？`, '删除提示', {
        type: 'warning',
        confirmButtonText: '确定',
        cancelButtonText: '取消'
      })
        .then(() => {
          deleteApplicationApi(uuid)
            .then(() => Message.success('删除成功'))
            .catch(error => Message.error(parseError(error)))
            .finally(() => this.search());
        })
        .catch(() => {});
    }
  }
};
</script>
<style lang="scss" scoped>
.application-list-container {
  padding: 10px;
  .orgnization-tag {
    margin-left: 4px;
    margin-right: 4px;
  }
}
.receive-device-footer {
  padding-top: 10px;
}
</style>
